<?php

require_once("../includes/smarty/Smarty.class.php");

$smarty = new Smarty();

$installable = true;
$required_php_version = '5.2.6';

$smarty->assign('good','<font color="#009900"><b>Good</b></font>');
$smarty->assign('bad','<font color="#990000"><b>Bad</b></font>');
$smarty->assign('available','<font color="#009900"><b>Available</b></font>');
$smarty->assign('not_available','<font color="#009900"><b>Not available</b></font>');

$smarty->assign('required_php_version',$required_php_version);
$smarty->assign('php_version',PHP_VERSION);
$smarty->assign('mode',$_GET['action']);

if ($_GET['action'] == "")
{
	$php_version = $good;
	$php_valid = version_compare(PHP_VERSION, $required_php_version, '>=');
	$mysqli_valid = extension_loaded('mysqli');

	$smarty->assign('php_valid',$php_valid);
	$smarty->assign('mysqli_valid',$mysqli_valid);

	$installable = $php_valid && $mysqli_valid;
	$smarty->assign('installable',$installable);
}

else if ($_GET['action'] == "install")
{
	//echo $_POST['db_server'];
	$sqlfile = file_get_contents ('tablecreate.sql');
	
	$sqlfile = str_replace(array("prefix","dbname"),array($_POST['d_prefix'],$_POST['d_database']),$sqlfile);
	//echo $sqlfile;
	
	$link = mysql_connect($_POST['d_server'], $_POST['d_username'], $_POST['d_password']);
	if (!$link)
	{
		die('<p>Could not connect to database server: '.mysql_error().'</p>');
	}
	
	echo "<p>Connected to database</p>";

	while (strlen($sqlfile) > 0)
	{
		$q = substr($sqlfile,0,stripos($sqlfile,";"));
		$sqlfile = substr($sqlfile, strlen($q) + 1);
		echo "Executing: <i>$q</i> ";
		$result = mysql_query($q);
		if (!$result)
		{
			die('Could not perform query: '.mysql_error().'<br/><br/>'.$query);
		}
		echo "<font color='green'>done</font><br/>";
	}
	
	echo "Writing config file.<br/>";
	
	$config_location = "../includes/config.php";
	$config_file = fopen($config_location, 'w');
	
	$config_template = "default_config.php";
	$config_contents = file_get_contents($config_template);
	
	$config_contents = str_replace(
		array(	"d_server",
				"d_username",
				"d_password",
				"d_database",
				"d_prefix",
				"d_root_folder",
				"d_sitename"),
		array(	$_POST['d_server'],
				$_POST['d_username'],
				$_POST['d_password'],
				$_POST['d_database'],
				$_POST['d_prefix'],
				$_POST['d_root_folder'],
				$_POST['d_sitename']),
		$config_contents);
	
	fwrite($config_file,$config_contents);
	fclose($config_file);
	
	// Now to use internal functions for admin setup
	require_once("../includes/database.php");
	require_once("../includes/users.php");
	
	db_setup();
	create_user($_POST['d_admin_username'], $_POST['d_admin_username'], "admin", "admin", $_POST['d_admin_password'], $_POST['d_admin_email'], 0, 1, 0);
	
	echo "<p>Done</p><p><textarea rows='20' cols='50'>$config_contents</textarea>";
	echo "<p><a href='".$_POST['d_root_folder']."'>Go to index (main site)</a></p>";
}

$smarty->display("install.tpl");

?>
